<?php

// 关键词管理类

namespace Home\Controller;

// use Think\Controller;
class KeywordController extends BaseController {

    public function index() {
        $mod = D('keyword');
        $page = I('page', 1);

        $where = array('app_id' => $this->app['id'], 'state' => 0);
        $count = $mod->where($where)->count();
        $data = $mod->where($where)->page($page . ',20')->order('id desc')->select();
        foreach ($data as &$v) {
            $sid[] = $v['sid'];
        }
        $sdatas = D('sucai')->where(array('id' => array('in', $sid)))->select();
        foreach ($sdatas as &$vv) {
            $sdata[$vv['id']] = $vv;
        }
        foreach ($data as &$vvv) {
            $vvv['sdata'] = $sdata[$vvv['sid']];
        }
        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->assign('prev', ($page > 1) ? $page - 1 : 1);
        $this->assign('next', ($page > ceil($count / 20)) ? $page + 1 : ceil($count / 20));
        $this->assign('count', ceil($count / 20));
        $this->display();
    }

    public function add() {
        $mod = D('sucai');
        $page = I('page', 1);
        $where = array('app_id' => $this->app['id'], 'state' => 0);
        $count = $mod->where($where)->count();
        $data = $mod->where($where)->field('id,title')->page($page . ',20')->order('id desc')->select();
        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->assign('prev', ($page > 1) ? $page - 1 : 1);
        $this->assign('next', ($page > ceil($count / 20)) ? $page + 1 : ceil($count / 20));
        $this->assign('count', ceil($count / 20));
        $this->assign('scount', $count);
        $this->display();
    }

    public function do_add() {
        $mod = D('keyword');
        $result = $this->befort_add();
        if (!$result) {
          
            if (($data = $mod->create($_GET))) {

                $data['app_id'] = $this->app['id'];
                if (($id = $mod->add($data))) {
                    $this->ajaxReturn(array('id' => $id, 'msg' => '添加成功！'));
                }
            }
            $this->ajaxReturn(array('id' => '', 'msg' => '添加失败！'));
        } else {
            $mod->where("id=".$result["id"])->save(array("word"=>$_GET["word"]));
        }
    }

    private function befort_add() {

        $sid = $_GET["sid"];
        $result = M("Keyword")->where("sid=" . $sid)->find();
        if ($result) {
            return $result;
        } else {
            return FALSE;
        }
    }
    
    public function updateKW(){
        $data = $_POST;
        $where=array("type"=>$data["type"],"sid"=>$data["sid"]);
        $save["word"] = $data["word"];
        
        M("Keyword")->where($where)->save($save);
    }

}